package com.xtpt.disaster.config;


import com.xtpt.disaster.common.consts.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class BaseEnumConverter implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToIEum<>(targetType);
    }

    @SuppressWarnings("all")
    private static class StringToIEum<T extends BaseEnum> implements Converter<String, T> {
        private Class<T> targerType;
        public StringToIEum(Class<T> targerType) {
            this.targerType = targerType;
        }
        @Override
        public T convert(String source) {
            if (isEmpty(source)) {
                return null;
            }
            return (T) BaseEnumConverter.getIEnum(this.targerType, source);
        }
    }

    public static <T extends BaseEnum> Object getIEnum(Class<T> targerType, String source) {
        for (T enumObj : targerType.getEnumConstants()) {
            if (source.equals(String.valueOf(enumObj.getValue()))) {
                return enumObj;
            }
        }
        return null;
    }
    /**
     * 判断对象是否为空(包括"")
     * @param obj
     * @return
     */
    public static boolean isEmpty(Object obj){
        if(obj == null) return true;
        String str = obj.toString().trim();
        return "".equals(str) || "null".equalsIgnoreCase(str);
    }
}